package cn.taketoday.live.handler;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;

import cn.taketoday.live.WebSocketMessage;
import cn.taketoday.live.config.GlobalData;
import cn.taketoday.live.config.settings.ThankFollowSetConf;
import cn.taketoday.live.config.settings.ThankWelcomeSetConf;
import cn.taketoday.live.data.Interact;
import cn.taketoday.live.data.enums.ShieldMessage;
import cn.taketoday.live.utils.JodaTimeUtils;

/**
 * @author TODAY 2021/5/17 23:33
 */
public class InteractWordCommandHandler implements CommandHandler {

  @Override //INTERACT_WORD
  public void handle(CommandContext context) throws Exception {
    final StringBuilder stringBuilder = new StringBuilder(32);
    final JSONObject jsonObject = context.getOriginal();
    final JSONObject data = jsonObject.getJSONObject("data");
    final short msgType = data.getShort("msg_type");  // msg_type 1 为进入直播间 2 为关注 3为分享直播间
    if (context.contains(ShieldMessage.is_follow) && msgType == 2) {// 关注
      Interact interact = data.toJavaObject(Interact.class);
      stringBuilder.append(JodaTimeUtils.formatDateTime(System.currentTimeMillis())).append(":新的关注:")
              .append(interact.getUname()).append(" 关注了直播间");
      //控制台打印
      printTerminal(context, stringBuilder);
      //前端弹幕发送
      context.sendMessage(WebSocketMessage.of("follow", interact));
      stringBuilder.delete(0, stringBuilder.length());
    }
    if (context.contains(ShieldMessage.is_followThank) && !GlobalData.IS_SHIELD_FOLLOW) {
      if (msgType == 2) {
        Interact interact = data.toJavaObject(Interact.class);
        parseFollowSetting(interact);
      }
    }
    //欢迎进入直播间
    if (context.contains(ShieldMessage.is_welcome_all) && msgType == 1) {
      Interact interact = data.toJavaObject(Interact.class);
      stringBuilder.append(JodaTimeUtils.formatDateTime(System.currentTimeMillis())).append(":新的访客:")
              .append(interact.getUname()).append(" 进入了直播间");
      printTerminal(context, stringBuilder);
      //前端显示
      stringBuilder.delete(0, stringBuilder.length());
    }
    if (context.contains(ShieldMessage.is_welcomeThank)
            && !GlobalData.IS_SHIELD_WELCOME
            && msgType == 1) {
      Interact interact = data.toJavaObject(Interact.class);
      parseWelcomeSetting(interact);
    }

    //打印测试用
    // msg_type = JSONObject.parseObject(jsonObject.getString("data")).getShort("msg_type");
    // if(msg_type!=3&&msg_type!=2) {
    // LOGGER.debug("直播间信息:::" + message);
    // }
  }

  private void printTerminal(CommandContext context, StringBuilder stringBuilder) {
    //控制台打印
    if (context.contains(ShieldMessage.is_cmd)) {
      System.out.println(stringBuilder);
    }
    //日志
    if (GlobalData.logThread != null && !GlobalData.logThread.FLAG) {
      GlobalData.logString.add(stringBuilder.toString());
      synchronized(GlobalData.logThread) {
        GlobalData.logThread.notify();
      }
    }
  }

  public synchronized void parseWelcomeSetting(Interact interact) throws Exception {
    if (interact != null && !StringUtils.isEmpty(GlobalData.USERCOOKIE)) {

      final ThankWelcomeSetConf welcome = GlobalData.centerSetConf.getWelcome();
      final double delayTime = welcome.getDelayTime(); // TODO
      final short num = welcome.getNum(); // TODO
      final String welcomes = welcome.getWelcomes();
      final String thankString = buildThankString(welcomes);
      final String uname = interact.getUname();
      String thankWelcomeString = StringUtils.replace(thankString, "%uNames%", uname);
      BarrageHandler.send(thankWelcomeString);
    }
  }

  public synchronized void parseFollowSetting(Interact interact) throws Exception {
    if (interact != null && !StringUtils.isEmpty(GlobalData.USERCOOKIE)) {
      final String uname = interact.getUname();
      final ThankFollowSetConf follow = GlobalData.centerSetConf.getFollow();

      final String follows = follow.getFollows();
      final String thankString = buildThankString(follows);
      String thankFollowStr = StringUtils.replace(thankString, "%uNames%", uname);
      BarrageHandler.send(thankFollowStr);
    }
  }

  public static String buildThankString(String thankStr) {
    String[] thankWelcomeStrs = null;
    if (StringUtils.indexOf(thankStr, "\n") != -1) {
      thankWelcomeStrs = StringUtils.split(thankStr, "\n");
    }
    if (thankWelcomeStrs != null && thankWelcomeStrs.length > 1) {
      return thankWelcomeStrs[(int) Math.ceil(Math.random() * thankWelcomeStrs.length) - 1];
    }
    return thankStr;
  }

}
